using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// paddle的移动
/// </summary>
public class Paddle : MonoBehaviour
{
    public new Rigidbody2D rigidbody2D { get; private set; }
    public Vector2 direction{ get; private set; }
    public float speed = 30f;
    public float maxBounceAngle = 75f;
    public GameObject ballPrefab;//小球预制体


    private void Awake()
    {
        this.rigidbody2D = GetComponent<Rigidbody2D>();
    }

    //输入检测
    private void Update()
    {
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            this.direction = Vector2.left;
        }else if(Input.GetKey(KeyCode.D) ||Input.GetKey(KeyCode.RightArrow))
        {
            this.direction = Vector2.right;
        }
        else
        {
            this.direction = Vector2.zero;
        }
    }

    //球拍的移动
    private void FixedUpdate()
    {
        if (this.direction!=Vector2.zero)
        {
            this.rigidbody2D.AddForce(this.direction * speed);
        }
    }

    /// <summary>
    /// 重置球拍
    /// </summary>
    public void RestPaddle()
    {
        this.transform.position = new Vector2(0f,transform.position.y);
        this.rigidbody2D.velocity = Vector2.zero;
    }

   
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Ball ball = collision.gameObject.GetComponent<Ball>();
        Prop prop = collision.gameObject.GetComponent<Prop>();

        //检测与球的碰撞，实现正在意义上的物理反射（也可以不用）
        if (ball!=null)
        {
            Collider2D paddle = collision.otherCollider;

            Vector2 ballDirection = ball.rigidbody2D.velocity.normalized;
            Vector2 contactDistance = paddle.bounds.center - ball.transform.position;

            // 根据接触距离旋转球的方向
            float bounceAngle = (contactDistance.x / paddle.bounds.size.x) * maxBounceAngle;
            ballDirection = Quaternion.AngleAxis(bounceAngle, Vector3.forward) * ballDirection;

            // 重新定义球的新方向
            ball.rigidbody2D.velocity = ballDirection * ball.rigidbody2D.velocity.magnitude;

        }
        
        //销毁道具以及获取道具操作
        if (prop != null)
        {
            Destroy(prop.gameObject);
            if (prop.CurrType == Prop.Prop_Type.Life)
            {
                //增加生命值
                GameManager.Instance.IncreaseLives();
            }else if (prop.CurrType == Prop.Prop_Type.More)
            {
                //多球逻辑
                for (int i = 0; i < prop.moreNum; i++)
                {
                    GameObject ballItem = Instantiate(ballPrefab);
                    ballItem.GetComponent<Ball>().RestBall();

                }
            }
        }
    }
}
